//
//  BasicInfoEditController.m
//  3DModelCollector
//
//  Created by Jing Zhang on 7/9/12.
//  Copyright (c) 2012 Tencent. All rights reserved.
//

#import "BasicInfoEditController.h"
#import "Utility.h"

typedef struct SubControlPositionRecord_
{
    int viewYPos;
    int nameTextFieldYPos;
    int addressTextboxYPos;
    int typeTextViewYPos;
    int baseAccuracyTextFieldYPos;
    int divisionTextFieldYPos;
    int businessRegionTextFieldYPos;
    int remarkTextViewYPos;
}
SubControlPositionRecord;

@interface BasicInfoEditController ()

@property (retain, nonatomic) IBOutlet UILabel *IDLabel;
@property (retain, nonatomic) IBOutlet UITextField *nameTextField;
@property (retain, nonatomic) IBOutlet UITextField *addressTextField;
@property (retain, nonatomic) IBOutlet UITextField *typeTextField;
@property (retain, nonatomic) IBOutlet UITextField *accurateTextField;
@property (retain, nonatomic) IBOutlet UITextField *divisionTextField;
@property (retain, nonatomic) IBOutlet UITextField *businessRegionTextField;
@property (retain, nonatomic) IBOutlet UITextView *remarkTextView;
//@property (retain, nonatomic) UIToolbar *inputAccessoryToolbar;

@property (nonatomic, assign) UIView*  activeView;

@property (nonatomic, retain) NSArray* typePickerSource;
@property (nonatomic, retain) NSArray* accuratePickerSource;

- (IBAction)onTextFieldBeginEditing:(id)sender;
- (void)onClickFinishInput:(id)sender;
- (void)onClickCancelBarButton:(id)sender;
- (void)onClickOKBarButton:(id)sender;

- (void)animateView:(NSInteger)moveUpHeight;
- (void)setInputAccessoryView;
- (void)setTextForControls;
- (BOOL)checkProfile;

@end

@implementation BasicInfoEditController

@synthesize IDLabel = _IDLabel;
@synthesize nameTextField = _nameTextField;
@synthesize addressTextField = _addressTextField;
@synthesize typeTextField = _typeTextField;
@synthesize accurateTextField = _accurateTextField;
@synthesize divisionTextField = _divisionTextField;
@synthesize businessRegionTextField = _businessRegionTextField;
@synthesize remarkTextView = _remarkTextView;

@synthesize activeView = _activeView;

@synthesize typePickerSource = _typePickerSource;
@synthesize accuratePickerSource = _accuratePickerSource;

@synthesize basicInfo = _basicInfo;
@synthesize delegate = _delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"基本信息编辑";
        
        UIBarButtonItem* cancelBarButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(onClickCancelBarButton:)];
        self.navigationItem.leftBarButtonItem = cancelBarButton;
        [cancelBarButton release];
        
        UIBarButtonItem* okBarButton = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleBordered target:self action:@selector(onClickOKBarButton:)];
        self.navigationItem.rightBarButtonItem = okBarButton;
        [okBarButton release];
        
        // 初始化两个选择列表
        NSMutableArray* typeArray = [[NSMutableArray alloc] initWithCapacity:1];
        for (int i = BT_House; i <= BT_Other; i++) {
            NSString* desc = [Utility buildingTypeToString:i];
            [typeArray addObject:desc];
        }
        self.typePickerSource = [NSArray arrayWithArray:typeArray];
        [typeArray release];
        
        NSMutableArray* accurateArray = [[NSMutableArray alloc] initWithCapacity:1];
        for (int i = BA_Exact; i <= BA_Unknown; i++) {
            NSString* desc = [Utility baseAccuracyToString:i];
            [accurateArray addObject:desc];
        }
        self.accuratePickerSource = [NSArray arrayWithArray:accurateArray];
        [accurateArray release];
    }
    return self;
}

- (void)dealloc {
    
    [_IDLabel release];
    [_nameTextField release];
    [_addressTextField release];
    [_typeTextField release];
    [_accurateTextField release];
    [_divisionTextField release];
    [_businessRegionTextField release];
    [_remarkTextView release];
   
    self.activeView = nil;
    self.typePickerSource = nil;
    self.accuratePickerSource = nil;
    
    self.basicInfo = nil;
    self.delegate = nil;
    
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    [self setInputAccessoryView];
    [self setTextForControls];
}

- (void)viewDidUnload
{
    [self setIDLabel:nil];
    [self setNameTextField:nil];
    [self setAddressTextField:nil];
    [self setTypeTextField:nil];
    [self setAccurateTextField:nil];
    [self setDivisionTextField:nil];
    [self setBusinessRegionTextField:nil];
    [self setRemarkTextView:nil];

    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - [UITextFieldDelegate]

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    NSLog(@"textFieldDidBeginEditing");
    //    self.activeView = textField;
    
}

#pragma mark - [UITextViewDelegate]

- (void)textViewDidBeginEditing:(UITextView *)textView {
    
    self.activeView = textView;
    
    CGFloat bottom = textView.frame.origin.y + textView.frame.size.height;
    
    CGFloat accessoryBottm = 416 - 44 - textView.inputAccessoryView.superview.frame.size.height;
    
    if (bottom > accessoryBottm) {
        [self animateView:(bottom - accessoryBottm)];
    }
}

#pragma mark - [UIPickerViewDataSource]

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    
    if (pickerView.tag == 10) {
        return 1;
    }
    else if (pickerView.tag == 20) {
        return 1;
    }
    else {
        return 0;
    }
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    if (pickerView.tag == 10) {
        return self.typePickerSource.count;
    }
    else if (pickerView.tag == 20) {
        return self.accuratePickerSource.count;
    }
    else {
        return 0;
    }
}

#pragma mark - [UIPickerViewDelegate]

- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
    if (pickerView.tag == 10) {
        return [self.typePickerSource objectAtIndex:row];
    }
    else if (pickerView.tag == 20) {
        return [self.accuratePickerSource objectAtIndex:row];
    }
    else {
        return @"";
    }
}

#pragma mark - [Private methods] 

- (IBAction)onTextFieldBeginEditing:(id)sender {
    NSLog(@"onTextFieldBeginEditing");
    UITextField* textField = (UITextField*)sender;
    
    if (textField == self.typeTextField) {
    }
    else if (textField == self.accurateTextField) {
        
    }
    
    //    [textField becomeFirstResponder];
    self.activeView = textField;
    
    CGFloat bottom = textField.frame.origin.y + textField.frame.size.height;
    
    CGFloat accessoryBottom = 416 - (textField.inputAccessoryView.frame.size.height + 216 + 44);
    
    if (bottom > accessoryBottom) {
        [self animateView:(bottom - accessoryBottom)];
    }
}

- (void)onClickFinishInput:(id)sender {
    NSLog(@"click finish button");
    
    if (self.activeView != nil) {
        
        if (self.activeView == self.typeTextField) {
            UIPickerView* picker = (UIPickerView*)self.typeTextField.inputView;
            int index = [picker selectedRowInComponent:0];
            NSString* str = [self pickerView:picker titleForRow:index forComponent:0];
            self.typeTextField.text = str;
        }
        else if (self.activeView == self.accurateTextField) {
            UIPickerView* picker = (UIPickerView*)self.accurateTextField.inputView;
            int index = [picker selectedRowInComponent:0];
            NSString* str = [self pickerView:picker titleForRow:index forComponent:0];
            self.accurateTextField.text = str;
        }
        
        [self.activeView resignFirstResponder];
        [self animateView:self.view.frame.origin.y];
    }
    
    self.activeView = nil;
}

- (void)onClickCancelBarButton:(id)sender {
    
    [self.navigationController dismissModalViewControllerAnimated:YES];
}

- (void)onClickOKBarButton:(id)sender {
    
    if ([self checkProfile]) {
        if (self.delegate != nil) {
            [self.delegate updateBuildingBasicInfo:self.basicInfo];
        }
        
        [self.navigationController dismissModalViewControllerAnimated:YES]; 
    }
}

- (void)animateView:(NSInteger)moveUpHeight
{
    CGRect rect = self.view.frame;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    
    //    if (moveUpHeight > 0) 
    {
        rect.origin.y -= moveUpHeight;
    }
    
    self.view.frame = rect;
    [UIView commitAnimations];
}

- (void)setInputAccessoryView {
    
    UIBarButtonItem* spaceBarItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace                            target:nil                                         action:nil];
    
    UIBarButtonItem* finishBarItem = [[UIBarButtonItem alloc] initWithTitle:@"完成"                                             style:UIBarButtonItemStyleDone                          target:self action:@selector(onClickFinishInput:)];
    
    UIToolbar* accessoryToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    accessoryToolbar.barStyle = UIBarStyleBlackTranslucent;
    [accessoryToolbar setItems:[NSArray arrayWithObjects:spaceBarItem, finishBarItem, nil]];
    [spaceBarItem release];
    [finishBarItem release];
    
    self.nameTextField.inputAccessoryView = accessoryToolbar;
    self.addressTextField.inputAccessoryView = accessoryToolbar;
    self.typeTextField.inputAccessoryView = accessoryToolbar;
    self.accurateTextField.inputAccessoryView = accessoryToolbar;
    self.divisionTextField.inputAccessoryView = accessoryToolbar;
    self.businessRegionTextField.inputAccessoryView = accessoryToolbar;
    self.remarkTextView.inputAccessoryView = accessoryToolbar;
    
    [accessoryToolbar release];
    
    // InputView for type and base accurate
    UIPickerView* typePicker = [[UIPickerView alloc] initWithFrame:CGRectZero];
    typePicker.tag = 10;
    typePicker.dataSource = self;
    typePicker.delegate = self;
    typePicker.showsSelectionIndicator = YES;
    self.typeTextField.inputView = typePicker;
    [typePicker release];
    
    UIPickerView* accuratePicker = [[UIPickerView alloc] initWithFrame:CGRectZero];
    accuratePicker.tag = 20;
    accuratePicker.dataSource = self;
    accuratePicker.delegate = self;
    accuratePicker.showsSelectionIndicator = YES;
    self.accurateTextField.inputView = accuratePicker;
    [accuratePicker release];
}

- (void)setTextForControls {
    
    if (self.basicInfo == nil) {
        return;
    }
    
    self.IDLabel.text = [NSString stringWithFormat:@"%d", self.basicInfo.UID];
    self.nameTextField.text = self.basicInfo.name;
    self.addressTextField.text = self.basicInfo.address;
    self.typeTextField.text = [Utility buildingTypeToString:self.basicInfo.type];
    self.divisionTextField.text = self.basicInfo.division;
    self.businessRegionTextField.text = self.basicInfo.businessRegion;
    self.remarkTextView.text = self.basicInfo.remark;
}

- (BOOL)checkProfile {
    
    NSString* alertText = @"";
    if ([self.nameTextField.text isEqualToString:@""]) {
        alertText = @"请输入名称";
    }
    else if ([self.addressTextField.text isEqualToString:@""]) {
        alertText = @"请输入地址";
    }
    else if ([self.typeTextField.text isEqualToString:@""]) {
        alertText = @"请选择建筑物类型";
    }
    else if ([self.divisionTextField.text isEqualToString:@""]) {
        alertText = @"请输入区划信息";
    }
    else if ([self.businessRegionTextField.text isEqualToString:@""]) {
        alertText = @"请输入商圈信息";
    }
    
    if (![alertText isEqualToString:@""]) {
        UIAlertView* alertDialog = [[UIAlertView alloc] initWithTitle:nil message:alertText delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertDialog show];
        [alertDialog release];
        return NO;
    }
    
    // Update data
    self.basicInfo.name = self.nameTextField.text;
    self.basicInfo.address = self.addressTextField.text;
    self.basicInfo.type = [Utility stringToBuildingType:self.typeTextField.text];
    self.basicInfo.division = self.divisionTextField.text;
    self.basicInfo.businessRegion = self.businessRegionTextField.text;
    self.basicInfo.remark = self.remarkTextView.text;
    
    return YES;
}

@end
